<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同状态" prop="carStatus">
        <el-select v-model="queryParams.status" placeholder="请选择合同状态" class="custom-select">
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:contracts:add']"
          class="custom-button"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:contracts:edit']"
          class="custom-button"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:contracts:remove']"
          class="custom-button"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:contracts:export']"
          class="custom-button"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractsList" @selection-change="handleSelectionChange" class="custom-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同ID" align="center" prop="id" />
      <el-table-column label="合同编号" align="center" prop="contractNumber" />
      <el-table-column label="房源地址" align="center" prop="propertyAddress" />
      <el-table-column label="签约日期" align="center" prop="signingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租期开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租期结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="租金金额" align="center" prop="rentAmount" />
      <el-table-column label="支付周期" align="center" prop="paymentCycle" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_cycle" :value="scope.row.paymentCycle" />
        </template>
      </el-table-column>
      <el-table-column label="押金金额" align="center" prop="depositAmount" />
      <el-table-column label="租金递增条款" align="center" prop="rentIncreaseTerms" />
      <el-table-column label="房东ID" align="center" prop="landlordId" />
      <el-table-column label="租客ID" align="center" prop="tenantId" />
      <el-table-column label="附加条款" align="center" prop="additionalTerms" />
      <el-table-column label="电子签名" align="center" prop="electronicSignature" />
      <el-table-column label="签署时间" align="center" prop="signatureTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signatureTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解约日期" align="center" prop="terminationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.terminationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解约原因" align="center" prop="terminationReason" />
      <el-table-column label="解约条款" align="center" prop="terminationTerms" />
      <el-table-column label="解约协议" align="center" prop="terminationAgreement" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:contracts:edit']"
            class="custom-text-button"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:contracts:remove']"
            class="custom-text-button"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTermination(scope.row)"
            v-hasPermi="['business:contracts:edit']"
            v-if="scope.row.status != 4"
            class="custom-text-button"
          >发起解约</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="custom-form">
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="房源地址" prop="propertyAddress">
          <el-input v-model="form.propertyAddress" placeholder="请输入房源地址" />
        </el-form-item>
        <el-form-item label="签约日期" prop="signingDate">
          <el-date-picker clearable
            v-model="form.signingDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择签约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租期开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择租期开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租期结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择租期结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租金金额" prop="rentAmount">
          <el-input v-model="form.rentAmount" placeholder="请输入租金金额" />
        </el-form-item>
        <el-form-item label="支付周期" prop="paymentCycle">
          <el-select v-model="form.paymentCycle" placeholder="请输入支付周期">
            <el-option
              v-for="dict in dict.type.payment_cycle"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="押金金额" prop="depositAmount">
          <el-input v-model="form.depositAmount" placeholder="请输入押金金额" />
        </el-form-item>
        <el-form-item label="租金递增条款" prop="rentIncreaseTerms">
          <el-input v-model="form.rentIncreaseTerms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="房东ID" prop="landlordId">
          <el-input v-model="form.landlordId" placeholder="请输入房东ID" />
        </el-form-item>

        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择租客">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附加条款" prop="additionalTerms">
          <el-input v-model="form.additionalTerms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="电子签名" prop="electronicSignature">
          <el-input v-model="form.electronicSignature" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="签署时间" prop="signatureTime">
          <el-date-picker clearable
            v-model="form.signatureTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择签署时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解约日期" prop="terminationDate">
          <el-date-picker clearable
            v-model="form.terminationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择解约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解约原因" prop="terminationReason">
          <el-input v-model="form.terminationReason" placeholder="请输入解约原因" />
        </el-form-item>
        <el-form-item label="解约条款" prop="terminationTerms">
          <el-input v-model="form.terminationTerms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="解约协议" prop="terminationAgreement">
          <el-input v-model="form.terminationAgreement" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" class="custom-button">确 定</el-button>
        <el-button @click="cancel" class="custom-button">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 解约对话框 -->
    <el-dialog :title="terminationTitle" :visible.sync="terminationOpen" width="500px" append-to-body class="custom-dialog">
      <el-form ref="terminationForm" :model="terminationForm" :rules="terminationRules" label-width="80px" class="custom-form">
        <el-form-item label="解约日期" prop="terminationDate">
          <el-date-picker clearable
                          v-model="terminationForm.terminationDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择解约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解约原因" prop="terminationReason">
          <el-input v-model="terminationForm.terminationReason" placeholder="请输入解约原因" />
        </el-form-item>
        <el-form-item label="解约条款" prop="terminationTerms">
          <el-input v-model="terminationForm.terminationTerms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="解约协议" prop="terminationAgreement">
          <el-input v-model="terminationForm.terminationAgreement" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTerminationForm" class="custom-button">确 定</el-button>
        <el-button @click="cancelTermination" class="custom-button">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContracts, getContracts, delContracts, addContracts, updateContracts } from "@/api/business/contracts";
import { getUser } from "@/api/business/contracts"; // 引入 getUser 方法

export default {
  dicts: ["status","payment_cycle"],
  name: "Contracts",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      contractsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractNumber: null,
        propertyAddress: null,
        signingDate: null,
        startDate: null,
        endDate: null,
        status: null,
        rentAmount: null,
        paymentCycle: null,
        depositAmount: null,
        rentIncreaseTerms: null,
        landlordId: null,
        tenantId: null,
        additionalTerms: null,
        electronicSignature: null,
        signatureTime: null,
        terminationDate: null,
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null,
        createdAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractNumber: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
        propertyAddress: [
          { required: true, message: "房源地址不能为空", trigger: "blur" }
        ],
        signingDate: [
          { required: true, message: "签约日期不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "租期开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "租期结束日期不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "合同状态不能为空", trigger: "change" }
        ],
        rentAmount: [
          { required: true, message: "租金金额不能为空", trigger: "blur" }
        ],
        paymentCycle: [
          { required: true, message: "支付周期不能为空", trigger: "blur" }
        ],
        depositAmount: [
          { required: true, message: "押金金额不能为空", trigger: "blur" }
        ],
        landlordId: [
          { required: true, message: "房东ID不能为空", trigger: "blur" }
        ],
        tenantId: [
          { required: true, message: "租客ID不能为空", trigger: "blur" }
        ],
        signatureTime: [
          { required: true, message: "签署时间不能为空", trigger: "blur" }
        ],
      },
      users: [], // 新增用户数据数组
      terminationTitle: "",
      terminationOpen: false,
      terminationForm: {},
      terminationRules: {
        terminationReason: [
          { required: true, message: "解约原因不能为空", trigger: "blur" }
        ],
        terminationTerms: [
          { required: true, message: "解约条款不能为空", trigger: "blur" }
        ],
        terminationAgreement: [
          { required: true, message: "解约协议不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUsers(); // 页面加载时获取用户数据
  },
  methods: {
    /** 查询合同信息列表 */
    getList() {
      this.loading = true;
      listContracts(this.queryParams).then(response => {
        this.contractsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractNumber: null,
        propertyAddress: null,
        signingDate: null,
        startDate: null,
        endDate: null,
        status: null,
        rentAmount: null,
        paymentCycle: null,
        depositAmount: null,
        rentIncreaseTerms: null,
        landlordId: null,
        tenantId: null,
        additionalTerms: null,
        electronicSignature: null,
        signatureTime: null,
        terminationDate: null,
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null,
        createdAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams=null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContracts(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContracts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContracts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同信息编号为"' + ids + '"的数据项？').then(function() {
        return delContracts(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发起解约按钮操作 */
    handleTermination(row) {
      this.resetTerminationForm();
      this.terminationForm = { ...row, status: 4 }; // 设置状态为 4
      this.terminationOpen = true;
      this.terminationTitle = "发起解约";
    },
    /** 取消解约按钮操作 */
    cancelTermination() {
      this.terminationOpen = false;
      this.resetTerminationForm();
    },
    /** 重置解约表单 */
    resetTerminationForm() {
      this.terminationForm = {
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null
      };
      this.resetForm("terminationForm");
    },
    /** 提交解约表单 */
    submitTerminationForm() {
      this.$refs["terminationForm"].validate(valid => {
        if (valid) {
          updateContracts(this.terminationForm).then(response => {
            this.$modal.msgSuccess("解约成功");
            this.terminationOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/contracts/export', {
        ...this.queryParams
      }, `contracts_${new Date().getTime()}.xlsx`)
    },

    // 新增获取用户数据的方法
    getUsers() {
      getUser().then(response => {
        this.users = response.data;
      });
    },
  }
};
</script>

<style scoped>
.custom-select {
  width: 200px;
}

.custom-button {
  margin-bottom: 10px;
}

.custom-text-button {
  color: #409EFF;
  text-decoration: underline;
}

.custom-table {
  margin-top: 20px;
}

.custom-dialog {
  border-radius: 8px;
}

.custom-form {
  padding: 20px;
}
</style>
